<?php
namespace app\admin\controller;
use app\common\model\Exhibition as ExhibitionModel;
use app\common\model\Enroll as EnrollModel;
use think\Loader;
use think\Request;

class Exhibition extends Base{

    public function index(){

        $this->data['column'] = $this->column();

        $exhibitionModel  = ExhibitionModel::where([])->paginate(10);
        foreach($exhibitionModel as $key => &$exhibition){
            $exhibition->exhibition_time = date('Y-m-d',$exhibition->exhibition_time);
        }

        $this->data['model'] = $exhibitionModel;
        $this->data['title'] = '团购列表';
        return view('',$this->data);
    }


    public function add(){

        return view('',$this->data);
    }


    public function edit(Request $request){
        $id = $request->param('id');
        if(empty($id)){
            $this->error("没有权限");
        }

        $this->data['model'] = ExhibitionModel::get($id);
        $this->data['model']->exhibition_time = date('Y-m-d',$this->data['model']->exhibition_time);

        return view('',$this->data);
    }

    public function handle(Request $request)
    {
        $data = $request->post();
        $validate = Loader::validate('Exhibition');
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }

        $data['exhibition_time'] = strtotime($data['exhibition_time']);
        $data['op_user'] = $this->admin->id;
        if(empty($data['id'])){
            $data['add_time'] = $data['update_time'] = time();
            $model = new ExhibitionModel();
            $model->data($data);
            if($model->allowField(true)->save()){
                $this->success("新增成功");
            }
        }else{
            $data['update_time'] = time();
            $model = new ExhibitionModel();
            if($model ->allowField(true)->save($data,['id'=>$data['id']])){
                $this->success("更新成功");
            }
        }

        $this->error("操作失败");
    }

    /**
     * 要考虑到有人已经报名的互动
     * 所以 删除是不是应该都采用伪删除
     * 但是淘宝的产品已经买了的产品都是有删除的  所以是不是即使用户报名了，那么那些报名信息是存储在报名表中的，就算这里删除了，也不影响呢 就算活动的图片也保存过去
     * 暂时这么处理吧 已经报名的不能删除 测试的说话 再考虑这个问题
     * @param Request $request
     * @throws \think\exception\DbException
     */
    public function delete(Request $request){
        $id = $request->param('id');
        $model = ExhibitionModel::get($id);

        //查看已经报名的活动
        $count = EnrollModel::where(['exhibition_id'=>$id])->count();
        if($count){
            $this->error("该活动已经产生数据，不能删除。");
        }

        $res = $model->delete();
        if($res){
           $this->success('删除成功');
        }
        $this->error("删除失败");
    }

    public function column(){
        return [
            'title'=>'活动标题',
            'exhibition_time'=>'活动时间',
        ];
    }
}